package com.example.test.domain;

import com.example.test.annotation.AclItem;
import com.example.test.utils.SpringUtils;
import com.example.test.utils.StringUtils;
import lombok.Data;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;

import java.util.Locale;

/**
 * 权限控制项
 */
@Data
public class AccessControlItem {
    /**
     * 名称
     */
    private String name;

    /**
     * 权限码
     */
    private String code;

    /**
     * 描述
     */
    private String describe;

    /**
     * 匹配信息
     */
    private RequestMappingInfo requestMappingInfo;

    /**
     * 处理方法
     */
    private HandlerMethod handlerMethod;

    public AccessControlItem(AclItem aclItem, RequestMappingInfo requestMappingInfo, HandlerMethod handlerMethod) {
        MessageSource messageSource = SpringUtils.getBean(MessageSource.class);
        try {
            name = messageSource.getMessage(aclItem.name(), null, Locale.getDefault());
        }catch (NoSuchMessageException e){
            name = aclItem.name();
        }
        code = aclItem.code();
        if(StringUtils.isEmpty(code)) code = handlerMethod.getMethod().getName();
        describe = aclItem.describe();
        this.requestMappingInfo = requestMappingInfo;
    }
}
